<template>
	<view>
		<uni-popup ref="popup" :safe-area="false" style="z-index: 401;" @change="popupChange">
			<view class="bottom-popup">
				<view class="popup-title d-flex d-r psr a-center j-center">
                    <text class="text">体重打卡</text>
					<image @tap="close" class="title-icon" src="@/static/image/close.png"></image>
				</view>
				<view class="popup-date d-flex d-r a-center j-between">
					<view class="date-title d-flex d-r a-center">
						<view v-if="userWeightRecord.length>0" class="date-title-content d-flex d-r a-center">
							<view class="date-title-text">
                                <text class="text">{{isCurrentDate()?'今日体重记录':'当日体重记录'}}</text>
                            </view>
							<view class="date-title-number">
								<!--
                                <text class="text">近5条</text>
								-->
                            </view>
						</view>
						<view v-else class="date-title-content d-flex d-r a-center">
							<view class="date-title-text">
                                <text class="text">{{isCurrentDate()?'今日还未记录体重':'当日未记录体重'}}</text>
                            </view>
						</view>
					</view>
					<view class="date-date d-flex d-r a-center j-center" @tap="showDateTable">
						<view class="date-content d-flex d-c j-center">
                            <text class="text">{{moment(selectDate).format("M月D日")}}</text>
                            <text class="text">{{moment(selectDate).locale('zh-cn').format('dddd')}}</text>
                        </view>
						<image class="date-drop" src="@/static/image/drop-down.png"></image>
					</view>
				</view>
				<view class="popup-weight">
					<view v-for="(item,index) in userWeightRecord" class="popup-weight-row d-flex d-r a-center j-between" :class="{odd:index%2===1}">
						<view class="weight-row-type d-flex d-r a-center j-center">
                            <text class="text">{{item.type}}</text>
                        </view>
						<view class="weight-row-weight d-flex d-r a-center j-center">
                            <text class="text">{{item.weight}}KG</text>
                        </view>
						<view class="weight-row-image">
							<image class="weight-row-image" v-if="item.imgUrl.length>0" @tap="previewImage('preview'+index,item.imgUrl[0],item.imgUrl)" :id="`preview${index.toString()}`" :src="item.imgUrl[0]"></image>
						</view>
						<view class="weight-row-date">
                            <text class="text">{{moment(item.createTime,"YYYY-MM-DD HH:mm:ss").format("MM/DD HH:mm")}}</text>
                        </view>
						<!--
						<image @tap="delWeight(item.id)" class="weight-row-del" src="@/static/image/weight-del.png"></image>
						-->
					</view>
					<view class="popup-weight-divider"></view>
				</view>
				<view :class="`popup-image d-flex d-r ${imageUrlList.length==0?'j-center':''}`">
					<view class="popup-upload-image" v-for="(item,index) in imageUrlList">
						<image @tap="previewImage(imageUrlList)" class="upload-image-img" :src="item"></image>
						<view class="upload-image-del d-flex d-r a-center j-center">
							<image @tap="delImage(index)" class="image-del-icon" src="@/static/image/upload-image-del.png"></image>
						</view>
					</view>
					<view v-if="imageUrlList.length<4" class="upload-cell-button" @tap="imageUpload">
						<image class="cell-content-icon" src="@/static/image/checkPopup-camera.png"></image>
						<text class="cell-content-text">上传照片</text>
					</view>
				</view>
				<view class="popup-time d-flex d-r j-between wrap">
					<view v-for="(item,index) in timeOption" class="popup-time-content">
						<view @tap="changeTime(index)" class="popup-time-button d-flex d-r a-center j-center" :class="{'selected':index==time}">
                            <text class="text" :class="{'selected':index==time}">{{item}}</text>
                        </view>
					</view>
					<view class="popup-time-divider"></view>
				</view>
				<view class="popup-row">
					<picker-view :indicator-style="`height:${itemHeight}px;z-index: 0;`" :value="value" @change="bindChange" class="picker-view">
						<picker-view-column>
							<view class="item integer-row" :style="{height:itemHeight+'px'}" v-for="(item,index) in integers" :key="index">
                                <text class="text" :style="`${value[0]==index?select:noSelect}`">{{item}}</text>
                            </view>
						</picker-view-column>
						<picker-view-column>
							<view class="item decimal-row" :style="{height:itemHeight+'px'}" v-for="(item,index) in decimals" :key="index">
                                <text class="text" :style="`${value[1]==index?select:noSelect}`">{{item}}kg</text>
                            </view>
						</picker-view-column>
					</picker-view>
				</view>
				<view class="popup-button d-flex d-r j-center">
					<tm-button round="25" _style="font-weight: 600;" :disabled="addDisable" disabled-color="#ABABAB" :width="650" :shadow="-1"
					    :linear-color="[`${addDisable?'#ABABAB':'#64F1C5'}`, `${addDisable?'#ABABAB':'#29DBA3'}`]" linear="left" :fontSize="32" fontColor="#FFFFFF" @tap="determine"
					    label="打卡"></tm-button>
				</view>
			</view>
		</uni-popup>
	</view>
	<!--日期选择-->
	<dateTable
		ref="datePopup"
		:markDate="markDate"
		:initialDate="selectDate"
		color="#1DC691"
		minDate="2023-1-1"
		:zIndex="402"
		:maxDate="moment().format('YYYY-MM-DD')"
		@onGetDate="onGetDate"
		@changeMoon="onChangeMoon">
	</dateTable>
	<imagePreview ref="preview"></imagePreview>
</template>
<script setup lang="ts">
import { ref, defineEmits } from "vue";
import { BASE_URL } from "@/api/request";
import {showLoading,closeLoading} from '@/utils/utils';
import moment from "moment";
import "moment/dist/locale/zh-cn";
import dateTable from "@/components/dateTable.vue";
import { getGroupUserWeightRecord,addGroupWeightRecord,getGroupWeightDate,delWeightRecord } from "@/api/api";
import { userData as userDataStore } from "@/store/userData";
import {imageConvertArray,getHDImages} from '@/utils/format';
import imagePreview from "@/components/imagePreview.vue";
import { chooseImage } from "@/utils/utils";

const itemHeight = ref(uni.upx2px(70));
const select =`font-size: 40rpx;color:#1DC691;`
const noSelect =`font-size: 30rpx;color:#333333;`

interface Props {
	initialVlue?:string
	groupId?:string
	recordDate?:string
}
const props = withDefaults(defineProps<Props>(), {
	initialVlue:"60.0",
	groupId:"",
	recordDate:moment().format("YYYY-MM-DD")
})

const integers:any = ref([])
const decimals:any = ref([])
//初始化选择组件
for (let i = 0; i <= 120; i++) {
	integers.value.push(30 + i)
}
for (let i = 0; i <= 9; i++) {
	decimals.value.push("." + i)
}
const userData: any = userDataStore();
const popup = ref();
const userWeightRecord:any = ref([]);
const loadDate = () => {
	
	selectDate.value = moment(props.recordDate);
	let params = {
		userId:userData.id,
		groupId:props.groupId,
		recordDate:moment(selectDate.value).format("YYYY-MM-DD")
	}
	onChangeMoon(selectDate.value);//查询需要高亮显示的日期
	getGroupUserWeightRecord(params).then((res:any) => {
		if(res.success){
			userWeightRecord.value = res.data;
			userWeightRecord.value.forEach((item:any) => {
				item.imgUrl = imageConvertArray(item.imgUrl);
			});
		}
	});
}
//图片预览
const preview = ref();
const previewImage = (id:string,url:string,urls:any) => {
	//preview.value.open();
	uni.createSelectorQuery().select(`#${id}`).boundingClientRect(data => {  
		let param = {
			data:data,//图片的初始大小与位置
			url:url,//当前图片地址
			urls:getHDImages(urls)//预览集合图片地址
		}
	    preview.value.open(param);
	}).exec();
}
const open = () => {
    selectDate.value = new Date();
	popup.value.open("bottom");
	let weight = props.initialVlue.toString();
	if(weight==null||weight=='')weight = "60.0";
	if(weight.indexOf(".")===-1)weight+=".0";
	//初始默认值
	let integerText = weight.split(".")[0];
	let decimalText = "."+weight.split(".")[1];
	let integerIndex = integers.value.indexOf(Number(integerText));
	let decimaIndex = decimals.value.indexOf(decimalText);
	//初始化参数
	value.value = [integerIndex,decimaIndex];
	imageUrlList.value = [];
	time.value = 0;
	loadDate();
	isAddDisable();
	isDetermine = false;
}
const close = () => {
	popup.value.close()
}
const value = ref([164])

const bindChange = (e:any) => {
	const val = e.detail.value;
	value.value = val
}
//确定选择并给父页面传值
const emit = defineEmits(["onGetWeight","onCloseWeight"]);
let isDetermine  = false;//防止重复点击
const determine = () => {
	if(isDetermine)return;
	isDetermine = true;
	let Weight = integers.value[value.value[0]]+decimals.value[value.value[1]];
	let params = {
		groupId:props.groupId,
		userId:userData.id,
		recordDate:moment(selectDate.value).format("YYYY-MM-DD"),
		type:timeOption.value[time.value],
		weight:Weight,
		imgUrl:imageUrlList.value.toString()
	}
	addGroupWeightRecord(params).then((res:any) => {
		//isDetermine = false;
		if(res.success){
			uni.showToast({
			    title: "体重打卡成功",  
			    icon: 'success',  
			    duration: 1500,
			});
			emit("onGetWeight",Weight);
			close();
		}else{
			isDetermine = false;
			uni.showToast({
			    title: res.message,  
			    icon: 'none',  
			    duration: 1500,
			});
		}
	});
	//emit("onGetWeight", Weight);
	//close();//关闭
}
//选中时间
const time = ref(0);
const timeOption = ref(["起床空腹","早餐前","早餐后","午餐前","午餐后","晚餐前","晚餐后","入睡前"]);
const changeTime = (index:number) => {
	time.value = index;
}
const selectDate:any = ref(new Date());//选择的日期
const isCurrentDate = () =>{
	return moment(selectDate.value).format('YYYY-MM-DD') === moment().format('YYYY-MM-DD')
}
const datePopup = ref();
const markDate:any = ref([])//需要标识的日期
const showDateTable = () => {
	datePopup.value.open();
}
//日期选择
const onGetDate = (date:Date) => {
	selectDate.value = date;
	loadDate();//重新加载数据
	isAddDisable();//设置按钮是否可用
}
//日期选择器月份变更时操作
const onChangeMoon = (date:any) => {
	markDate.value = [];
	let param = {
		groupId:props.groupId,
		userId:userData.id,
		recordDate:moment(date).format("YYYY-MM-DD"),
	}
	getGroupWeightDate(param).then((res:any) => {
		res.data.forEach((item:any) => {
			markDate.value.push(item.recordDate);
			//console.log(markDate.value)
		})
	})
}

//判断添加按钮是否可用
const addDisable = ref(false);
const isAddDisable = () => {
	var threeDaysAgo = moment().subtract(3, 'days');  
	var today = moment();  
	var dateToCheck = moment(selectDate.value); // 这是你要检查的日期  
	if (dateToCheck.isBetween(threeDaysAgo, today)) {  
		addDisable.value = false;
	} else {  
		addDisable.value =  true;
		uni.showToast({
		    title: "三天外只可查看，不可修改",  
		    icon: 'none',  
		    duration: 2000,
		});
	}
}
const delWeight = (id:string) => {
	let param = {
		userId:userData.id,
		id:id,
	}
	delWeightRecord(param).then((res:any) => {
		if(res.success){
			uni.showToast({
			    title: res.message,  
			    icon: 'success',  
			    duration: 1500,
			});
			//emit("onGetWeight");
			loadDate();
			//close();
		}else{
			uni.showToast({
			    title: res.message,  
			    icon: 'none',  
			    duration: 1500,
			});
		}
	});
}

//图片上传
const imageUrlList:any = ref([])
const imageUpload = () => {
	chooseImage({
		count:1,
	    success: (chooseImageRes) => {
	        const token = uni.getStorageSync("api_token");
	        const tempFilePaths = chooseImageRes.tempFilePaths;
	        showLoading();
	        uni.uploadFile({
	            header: {
	                token,
	            },
	            url: `${BASE_URL}/file/upload`, //仅为示例，非真实的接口地址
	            filePath: tempFilePaths[0],
	            name: "file",
	            formData: {
                    'isCompress':1,
                },
	            success: (uploadFileRes) => {
	                let res: any;
	                 closeLoading();
	                try {
	                    res = JSON.parse(uploadFileRes.data);
	                } catch (error) {
	                    uni.showToast({
	                        icon: "none",
	                        title: '请稍后再试',
	                        duration: 1500,
	                    });
	                    return;
	                }
	                const { flag, data } = res;
	                if (flag !== 1) {
	                    uni.showToast({
	                        icon: "none",
	                        title: '上传失败,请稍后再试',
	                        duration: 1500,
	                    });
	                    return;
	                }
	                const { fileUrl } = data;
	                imageUrlList.value.push(fileUrl);
	            },
	            fail() {
	                closeLoading();
	                uni.showToast({
	                    icon: "none",
	                    title: '上传失败,请稍后再试',
	                    duration: 1500,
	                });
	            },
	        });
	    }
	});
}
const delImage = (index:number) => {
	imageUrlList.value.splice(index, 1);
}
const popupChange = (e:any) =>{
	if(!e.show){
		emit("onCloseWeight");//控件关闭时事件
	}
}

defineExpose({
  open,
  close
});
</script>
<style lang="scss" scoped>
.a-center {
    align-items: center;
}

.j-center {
    justify-content: center;
}

.j-between {
    justify-content: space-between;
}
.j-end {
    justify-content: flex-end;
}

.j-around {
    justify-content: space-around;
}

.d-flex d-r {
    display: flex;
}

.d-c {
    flex-direction: column;
}
.d-r {
    flex-direction: row;
}

.j-end {
    justify-content: flex-end;
}

.bottom-popup{
		padding-bottom: 40rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 0rpx 0rpx;
		.popup-title{
			height: 100rpx;
			/*
			border-bottom: 1rpx solid #E4E4E4;
			*/
			.text{
                font-size:32rpx;
			}
			.title-icon{
				position:absolute;
				top:32rpx;
				right: 30rpx;
				
				width: 36rpx;
				height: 36rpx;
			}
		}
		.popup-show{
			justify-content: space-between;
			height: 80rpx;
			padding: 0 30rpx 0 30rpx;
			.show-text{
				font-size: 32rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
			}
		}
		.popup-date{
			width: 750rpx;
			height: 100rpx;
			background: #FFFFFF;
			padding-left: 30rpx;
			padding-right: 30rpx;
			.date-title{
				flex: 1;
				.date-title-content{
					.date-title-text{
                        .text{
                            font-size: 32rpx;
                            font-weight: 500;
						    color: #333333;
                        }
					}
					.date-title-number{
                        .text{
                            padding-left: 13rpx;
                            line-height: 34rpx;
                            font-size: 28rpx;
                            font-family: PingFangSC-Regular, PingFang SC;
                            font-weight: 400;
                            color: #999999;
                        }
					}
				}
				
			}
			.date-date{
				.date-content{
					padding-left: 54rpx;
					padding-right: 10rpx;
                    .text{
                        font-size: 28rpx;
                        text-align: center;
                        font-weight: 400;
                        color: #333333;
                    }
				}
				.date-drop{
					width: 20rpx;
					height: 20rpx;
				}
			}
		}
		.popup-weight{
			position: relative;
			padding-bottom: 20rpx;

			.popup-weight-row{
				padding:0 30rpx;
				height: 60rpx;
                background-color: #EFFCF8; 
                &.odd{
                    background-color: #ffffff; 
                }

				.weight-row-type{
					width: 120rpx;
					height: 36rpx;
					background: #1DC691;
					border-radius: 4rpx;
                    .text{
                        font-size: 24rpx;
					    font-weight: 400;
					    color: #FFFFFF;
                    }
					
				}
				.weight-row-weight{
					text-align: center;
					width: 120rpx;
					height: 32rpx;
                    .text{
                        font-size: 28rpx;
                        font-weight: 500;
                        color: #333333;

                    }
				}
				.weight-row-image{
					width: 40rpx;
					height: 40rpx;
				}
				.weight-row-del{
					width: 40rpx;
					height: 40rpx;
				}
			}
			.popup-weight-divider{
				position: absolute;
				bottom: 0;
				left:50%;
				transform: translateX(-50%);
				
				width: 690rpx;
				height: 2rpx;
				background: #F5F5F5;
				border-radius: 3rpx;
			}
		}
		.popup-image{
			padding:40rpx;
			.popup-upload-image{
				position: relative;
				padding-right: 10rpx;
				.upload-image-img{
					width: 160rpx;
					height: 160rpx;
				}
				.upload-image-del{
					position:absolute;
					top:114rpx;
					left:114rpx;
					
					width: 40rpx;
					height: 40rpx;
					background: rgba(0,0,0,0.5);
					border-radius: 20rpx;
					.image-del-icon{
						width: 32rpx;
						height: 32rpx;
					}
				}
			}
			.popup-upload-image:nth-child(4) {  
			  padding-right: 0;
			}
			.upload-cell-button{
				display: flex;  
				flex-direction: column;  
				justify-content: center;  
				align-items: center; 
				  
				width: 160rpx;
				height: 160rpx;
				border-radius: 4rpx;
				border: 2rpx dashed #CCCCCC;
				.cell-content-icon{
					width: 50rpx;
					height: 50rpx;
				}
				.cell-content-text{
					padding-top: 20rpx;
					font-size: 24rpx;
					font-weight: 400;
					color: #CCCCCC;
				}
			}
		}
		.popup-time{
			position: relative;
			height: 180rpx;
			padding:20rpx 40rpx 0 40rpx;
			.popup-time-content{
				padding-bottom: 20rpx;
				.popup-time-button{
					width: 160rpx;
					height: 60rpx;
					border-radius: 30rpx;
					border: 1rpx solid #CCCCCC;
                    .text{
                        font-size: 28rpx;
                        font-weight: 400;
                        color: #333333;
                        &.selected{
                            color:#fff;
                            font-weight: 500;
                        }
                    }

                    &.selected{
                        background: #23E2A6;
						border:none;
                    }
					
				}
			}
			.popup-time-divider{
				position: absolute;
				bottom: 0;
                left:30rpx;
				
				width: 690rpx;
				height: 2rpx;
				background: #F5F5F5;
				border-radius: 3rpx;
			}
		}
		.popup-row {
            padding-bottom: 16rpx;
            .picker-view {
                height: 400rpx;
                margin-top: 20rpx;
            }
            .item {
                display: flex;
                flex-direction: row;
                align-items: center;
                .text{
                    font-size: 34rpx;
                    font-weight: 500;
                }

            }
            .integer-row {
                justify-content: flex-end;
                padding-right: 24rpx;
            }
            .decimal-row {
                padding-left: 31rpx;
            }
        }
		.popup-button{
			
		}
	}
</style>